<?php

defined("IN_IA") or exit("Access Denied");
include_once dirname(__FILE__) . "/autoload.inc.php";

class Slj123_tongchengModuleWxapp extends WeModuleWxapp
{
    public function __construct()
    {
        empty($_SESSION["openid"]) && $this->result(41009, "未登录");
    }

    public function doPagePay()
    {
        $post_costs = pdo_fetchcolumn("\nSELECT `top_time_cost`\nFROM " . tablename("slj123_pc_setting") . "\nWHERE `weid` = :weid", array(":weid" => $GLOBALS["_W"]["uniacid"]));
        if (!(!$post_costs || $post_costs <= 0 || $GLOBALS["_GPC"]["days"] == 0)) {
            $order = array("tid" => $no = date("YmdHis") . mt_rand(100, 999) . 00 . $GLOBALS["_GPC"]["days"], "user" => $_SESSION["openid"], "fee" => $post_costs * $GLOBALS["_GPC"]["days"], "title" => "购买置顶" . $GLOBALS["_GPC"]["days"] . "天");
            $pay_params = $this->pay($order);
            $pay_params["need_pay"] = !0;
            if (!is_error($pay_params)) {
                return $this->result(0, '', array_merge($pay_params, array("no" => $no)));
            }
            return $this->result(1, "支付失败，请重试", $pay_params);
        }
        $pay_params["need_pay"] = !1;
        return $this->result(1, "无需支付", $pay_params);
    }

    public function doPageStickyPayResult()
    {
        empty($GLOBALS["_GPC"]["no"]) || pdo_update("core_paylog", array("status" => 1), array("tid" => $GLOBALS["_GPC"]["no"]));
        $res = pdo_query("\nUPDATE " . tablename("slj123_pc_index") . "\nSET `top_time` = ADDTIME(FROM_UNIXTIME(UNIX_TIMESTAMP()), '{$GLOBALS["_GPC"]["days"]} 00:00:00')\nWHERE `id` = :id", array("id" => $GLOBALS["_GPC"]["index_id"]));
        $this->result(0, "成功", $res);
    }

    public function doPageCarpool()
    {
        return $this->result(0, "成功", \Slj123Tongcheng\model\SQL::one("\nSELECT *, DATEDIFF(`start_time`, NOW()) AS `RemainDays`, (`user_id` = :uid) AS `isMine`, :uid AS `Uid`, IF(\n  (DATEDIFF(`start_time`, NOW()) > 0),\n  CONCAT(DATEDIFF(`start_time`, NOW()), '天'),\n  IF(TIMEDIFF(`start_time`, NOW()) > 0, TIME_FORMAT(TIMEDIFF(`start_time`, NOW()), '%H小时'), '')\n) AS `PrettyRemain`\nFROM " . tablename("slj123_pc_index") . "\nWHERE `id` = :id;\nUPDATE " . tablename("slj123_pc_index") . "\nSET `view_count` = `view_count` + 1\nWHERE `id` = :id;", array(":id" => $GLOBALS["_GPC"]["index_id"], ":uid" => pdo_getcolumn("mc_mapping_fans", array("openid" => $_SESSION["openid"]), "uid"))));
    }

    public function doPageListCarpool()
    {
        global $_GPC, $_W;
        $errno = 0;
        $message = "返回消息";
        $where = '';
        $page = $_GPC["page"];
        $type = $_GPC["type"];
        $from_place = $_GPC["from_place"];
        $to_place = $_GPC["to_place"];
        $mid_place = $_GPC["mid_place"];
        $start_time = $_GPC["start_time"];
        $user_count = $_GPC["user_count"];
        if ($type && $type != "undefined") {
            $where .= "type = " . $type . " and ";
        }
        if ($from_place && $from_place != "undefined") {
            $where .= "from_place like " . "'%" . $from_place . "%'" . " and ";
        }
        if ($to_place && $to_place != "undefined") {
            $where .= "to_place like " . "'%" . $to_place . "%'" . " and ";
        }
        if ($mid_place && $mid_place != "undefined") {
            $where .= "mid_place like " . "'%" . $mid_place . "%'" . " and ";
        }
        if ($user_count && $user_count != "undefined") {
            $where .= "user_count >=" . $user_count . " and ";
        }
        $where .= "status = 1 and `weid` = " . $GLOBALS["_W"]["uniacid"];
        $tops = [];
        if ($page == 1) {
            pdo_query("\nUPDATE " . tablename("slj123_pc_index") . "\nSET `top_time` = NULL\nWHERE `top_time` < NOW();");
            $page -= 1;
            $order = "top_time desc, id DESC";
            $tops = $this->listCarpoolService($where, $page, 10, $order);
        } else {
            $page -= 1;
            $order = "top_time desc, id DESC";
            $datas = $this->listCarpoolService($where, $page, 10, $order);
            foreach ($datas as $item) {
                $tops[] = $item;
            }
        }
        foreach ($tops as &$v) {
            if ($v["start_time"] < date("Y-m-d H:i:s", TIMESTAMP) && $v["start_time"] > date("Y-m-d H:i:s", TIMESTAMP - 12 * 60 * 60)) {
                $v["overdue"] = 1;
            } else {
                if ($v["start_time"] < date("Y-m-d H:i:s", TIMESTAMP - 12 * 60 * 60)) {
                    $v["overdue"] = 0;
                } else {
                    $v["overdue"] = 2;
                }
            }
            $riqi = substr($v["start_time"], 0, 10);
            $today = date("Y-m-d");
            $mingtian = date("Y-m-d", strtotime("+1 day"));
            if ($riqi == $today) {
                $tmp = str_replace($riqi, '', $v["start_time"]);
                $v["start_time"] = "今天 " . $tmp;
            }
            if ($riqi == $mingtian) {
                $tmp = str_replace($riqi, '', $v["start_time"]);
                $v["start_time"] = "明天 " . $tmp;
            }
        }
        return $this->result($errno, $message, $tops);
    }

    public function listCarpoolService($where, $page, $listRows, $order)
    {
        $sql = "SELECT * FROM " . tablename("slj123_pc_index") . " WHERE " . $where . " ORDER BY " . $order . " LIMIT " . $page * 10 . "," . $listRows;
        $datas = pdo_fetchall($sql);
        foreach ($datas as $data) {
            $data["istop"] = false;
            if ($data["top_time"] > $data["postdate"] && $data["top_time"] > date("Y-m-d H:i:s")) {
                $data["istop"] = true;
            }
        }
        return $datas;
    }

    public function doPagePayResult()
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $wx_open_id = $_W["fans"]["openid"];
        $errno = 0;
        $message = "返回消息";
        $data["weid"] = $weid;
        $data["from_place"] = $_GPC["from_place"];
        $data["to_place"] = $_GPC["to_place"];
        $data["mid_place"] = $_GPC["mid_place"];
        $data["from_longitude"] = $_GPC["from_longitude"];
        $data["from_latitude"] = $_GPC["from_latitude"];
        $data["to_latitude"] = $_GPC["to_latitude"];
        $data["to_longitude"] = $_GPC["to_longitude"];
        $data["car"] = $_GPC["car"];
        $data["user_id"] = $_W["fans"]["uid"];
        $data["type"] = $_GPC["type"];
        $data["start_time"] = $_GPC["start_time"];
        $data["user_count"] = $_GPC["user_count"];
        $data["note"] = $_GPC["note"];
        $data["name"] = $_GPC["name"];
        $data["verified"] = $_GPC["verified"];
        $data["phone"] = $_GPC["phone"];
        $data["cost"] = $_GPC["cost"];
        $data["sex"] = $_GPC["sex"];
        $data["head"] = $_W["fans"]["avatar"];
        $data["status"] = 1;
        $res = pdo_insert("slj123_pc_index", $data);
        return $this->result($errno, $message, $res);
    }

    public function doPageGetmess()
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $id = $_GPC["id"];
        $errno = 0;
        $message = "返回消息";
        $sql = "SELECT * FROM " . tablename("slj123_pc_index") . " WHERE `id` = :id AND `weid` = :weid";
        $post_costs = pdo_fetch($sql, array(":id" => $id, ":weid" => $weid));
        return $this->result($errno, $message, $post_costs);
    }

    public function doPageUpdateCarpoolNew()
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $id = $_GPC["id"];
        $errno = 0;
        $message = "返回消息";
        $post_costs = pdo_update(`slj123_pc_index`, $data, array(":id" => $id, ":weid" => $weid));
        if (!(!$post_cost || $post_cost <= 0)) {
            $order = array("tid" => date("YmdHis"), "user" => $_SESSION["openid"], "fee" => floatval($post_cost), "title" => "更新拼车信息");
            $pay_param = $this->pay($order);
            if (!is_error($pay_param)) {
                $pay_params["need_pay"] = $needpay;
                $pay_params["pay_param"] = $pay_param;
                return $this->result($errno, $message, $pay_params);
            }
            return $this->result($errno, "支付失败，请重试", $pay_param);
        }
        $needpay = false;
        $pay_params["need_pay"] = $needpay;
        return $this->result($errno, "无需支付", $pay_params);
    }

    public function doPagePayResult1()
    {
        global $_GPC, $_W;
        $errno = 0;
        $message = "返回消息";
        $id = $_GPC["id"];
        $weid = $_W["uniacid"];
        $data["from_place"] = $_GPC["from_place"];
        $data["to_place"] = $_GPC["to_place"];
        $data["mid_place"] = $_GPC["mid_place"];
        $data["from_longitude"] = $_GPC["from_longitude"];
        $data["from_latitude"] = $_GPC["from_latitude"];
        $data["to_latitude"] = $_GPC["to_latitude"];
        $data["to_longitude"] = $_GPC["to_longitude"];
        $data["car"] = $_GPC["car"];
        $data["user_id"] = $_W["fans"]["uid"];
        $data["type"] = $_GPC["type"];
        $data["start_time"] = $_GPC["start_time"];
        $data["user_count"] = $_GPC["user_count"];
        $data["note"] = $_GPC["note"];
        $data["name"] = $_GPC["name"];
        $data["verified"] = $_GPC["verified"];
        $data["phone"] = $_GPC["phone"];
        $data["cost"] = $_GPC["cost"];
        $data["sex"] = $_GPC["sex"];
        $data["head"] = $_W["fans"]["avatar"];
        $data["status"] = 1;
        $res = pdo_update("slj123_pc_index", $data, array("id" => $id));
        return $this->result($errno, $message, $res);
    }

    public function doPageMyCollection($page = 1)
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $user_id = $_W["fans"]["uid"];
        $sql = "SELECT `people_post_cost`,`info_id` " . tablename("slj123_pc_collection") . " WHERE `weid` = :weid and `user_id` = :user_id";
    }

    public function doPageCollection()
    {
        global $_GPC, $_W;
        $errno = 0;
        $message = "返回消息";
        $weid = $_W["uniacid"];
        $user_id = $_W["fans"]["uid"];
        $info_id = $_GPC["id"];
        $data["weid"] = $weid;
        $data["user_id"] = $user_id;
        $data["info_id"] = $info_id;
        $sql = "SELECT * FROM " . tablename("slj123_pc_collection") . " WHERE `weid` = :weid and `user_id` = :user_id and `info_id` = :info_id";
        $a = pdo_fetch($sql, array(":weid" => $weid, ":user_id" => $user_id, ":info_id" => $info_id));
        if ($a) {
            $res = false;
        } else {
            $res = pdo_insert("slj123_pc_collection", $data);
        }
        return $this->result($errno, $message, $res);
    }

    public function doPageDmess()
    {
        global $_GPC, $_W;
        $errno = 0;
        $message = "返回消息";
        $id = $_GPC["id"];
        $weid = $_W["uniacid"];
        $res = pdo_delete("slj123_pc_index", array("id" => $id, "weid" => $weid));
        if ($res) {
            $a = 1;
        } else {
            $a = 2;
        }
        return $this->result($errno, $message, $a);
    }

    public function doPageCreateCarpoolNew()
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $wx_open_id = $_W["fans"]["openid"];
        $errno = 0;
        $message = "返回消息";
        $sql = "SELECT * FROM " . tablename("slj123_pc_user") . " WHERE `wx_open_id` = :wx_open_id AND `weid` = :weid";
        $user = pdo_fetch($sql, array(":wx_open_id" => $wx_open_id, ":weid" => $weid));
        if ($user) {
            $userinfo["name"] = $_GPC["name"];
            $userinfo["sex"] = $_GPC["sex"];
            $userinfo["phone"] = $_GPC["phone"];
            $userinfo["head"] = $_W["fans"]["avatar"];
            pdo_update("slj123_pc_user", $userinfo, array("id" => $user["id"]));
        }
        $sql = "SELECT `people_post_cost`,`car_post_cost`,`car_post_cost1`,`car_post_cost2` FROM " . tablename("slj123_pc_setting") . " WHERE `weid` = :weid";
        $post_costs = pdo_fetch($sql, array(":weid" => $weid));
        $people_post_cost = $post_costs["people_post_cost"];
        $find_type = $_GPC["find_type"];
        $needpay = true;
        if ($find_type == "people") {
            $post_cost = $post_costs["people_post_cost"];
        }
        if ($find_type == "car") {
            $post_cost = $post_costs["car_post_cost"];
        }
        if ($find_type == "car1") {
            $post_cost = $post_costs["car_post_cost1"];
        }
        if ($find_type == "car2") {
            $post_cost = $post_costs["car_post_cost2"];
        }
        if (!(!$post_cost || $post_cost <= 0)) {
            $order = array("tid" => date("YmdHis"), "user" => $_SESSION["openid"], "fee" => floatval($post_cost), "title" => "发布拼车信息");
            $pay_param = $this->pay($order);
            if (!is_error($pay_param)) {
                $pay_params["need_pay"] = $needpay;
                $pay_params["pay_param"] = $pay_param;
                return $this->result($errno, $message, $pay_params);
            }
            return $this->result($errno, "支付失败，请重试", $pay_param);
        }
        $needpay = false;
        $pay_params["need_pay"] = $needpay;
        return $this->result($errno, "无需支付", $pay_params);
    }

    public function doPageGetUserInfo()
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $wx_open_id = $_W["fans"]["openid"];
        $errno = 0;
        $message = "返回消息";
        $data["weid"] = $weid;
        $data["uid"] = $_W["fans"]["uid"];
        $data["wx_open_id"] = $_W["fans"]["openid"];
        $data["nickname"] = $_W["fans"]["nickname"];
        $data["sex"] = $_W["fans"]["sex"];
        $data["head"] = $_W["fans"]["avatar"];
        $sql = "SELECT * FROM " . tablename("slj123_pc_user") . " WHERE `weid` = :weid AND `wx_open_id` = :wx_open_id";
        $res = pdo_fetch($sql, array(":weid" => $weid, ":wx_open_id" => $wx_open_id));
        $info = $res;
        if ($wx_open_id) {
            if ($res["wx_open_id"]) {
                pdo_update("slj123_pc_user", $data, array("wx_open_id" => $_SESSION["openid"]));
            } else {
                pdo_insert("slj123_pc_user", $data);
                $info["nickname"] = $data["nickname"];
                $info["sex"] = $data["sex"];
            }
        }
        $sql = "SELECT `people_post_cost`,`isopen_renzheng`,`car_post_cost`,`car_post_cost1`,`car_post_cost2` FROM " . tablename("slj123_pc_setting") . " WHERE `weid` = :weid";
        $post_costs = pdo_fetch($sql, array(":weid" => $weid));
        $post_cost = $post_costs["car_post_cost"];
        $post_cost1 = $post_costs["car_post_cost1"];
        $post_cost2 = $post_costs["car_post_cost2"];
        $post_cost0 = $post_costs["people_post_cost"];
        $isopen_renzheng = $post_costs["isopen_renzheng"];
        $info["post_cost"] = $post_cost;
        $info["post_cost1"] = $post_cost1;
        $info["post_cost2"] = $post_cost2;
        $info["post_cost0"] = $post_cost0;
        $info["isopen_renzheng"] = $isopen_renzheng;
        unset($info["wx_open_id"]);
        $info['driving_license'] = empty($info['driving_license']) ? '/img/fdsfds_f.png' : 'http://' . $_SERVER['HTTP_HOST'] . '/attachment' . $info['driving_license'];
        $info['driving_permit'] = empty($info['driving_permit']) ? '/img/dsfd_se.png' : 'http://' . $_SERVER['HTTP_HOST'] . '/attachment' . $info['driving_permit'];
        $info['identity_back'] = empty($info['identity_back']) ? '/img/fdsfds_g.png' : 'http://' . $_SERVER['HTTP_HOST'] . '/attachment' . $info['identity_back'];
        $info['identity_front'] = empty($info['identity_front']) ? '/img/fdsfds_h.png' : 'http://' . $_SERVER['HTTP_HOST'] . '/attachment' . $info['identity_front'];
        return $this->result($errno, $message, $info);
    }

    public function doPageMyCarpool($page = 1)
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $user_id = $_W["fans"]["uid"];
        $page = $_GPC["page"];
        $page -= 1;
        $errno = 0;
        $message = "返回消息";
        $where = "user_id = " . $user_id . " and ";
        $where .= "status = 1";
        $order = "start_time asc";
        $datas = $this->listCarpoolService($where, $page, 10, $order);
        $sql = "SELECT * FROM " . tablename("slj123_pc_index") . " WHERE " . $where . " ORDER BY " . $order . " LIMIT " . $page * 10 . ",10";
        foreach ($datas as &$v) {
            if ($v["start_time"] < date("Y-m-d H:i:s", TIMESTAMP) && $v["start_time"] > date("Y-m-d H:i:s", TIMESTAMP - 12 * 60 * 60)) {
                $v["overdue"] = 1;
            } else {
                if ($v["start_time"] < date("Y-m-d H:i:s", TIMESTAMP - 12 * 60 * 60)) {
                    $v["overdue"] = 0;
                } else {
                    $v["overdue"] = 2;
                }
            }
            $riqi = substr($v["start_time"], 0, 10);
            $today = date("Y-m-d");
            $mingtian = date("Y-m-d", strtotime("+1 day"));
            if ($riqi == $today) {
                $tmp = str_replace($riqi, '', $v["start_time"]);
                $v["start_time"] = "今天 " . $tmp;
            }
            if ($riqi == $mingtian) {
                $tmp = str_replace($riqi, '', $v["start_time"]);
                $v["start_time"] = "明天 " . $tmp;
            }
        }
        return $this->result($errno, $message, $datas);
    }

    public function doPageGetBannerPathAndNotice()
    {
        global $_GPC, $_W;
        $weid = $_W["uniacid"];
        $errno = 0;
        $message = "返回消息";
        $sql = "SELECT * FROM " . tablename("slj123_pc_setting") . " WHERE `weid` = :weid";
        $config = pdo_fetch($sql, array(":weid" => $weid));
        $config["share_pic"] = tomedia($config["share_pic"]);
        $banners = explode(",", $config["banner"]);
        $banner_link = explode(",", $config["banner_link"]);
        $unitid = explode(",", $config["unitid"]);
        $i = 0;
        foreach ($banners as $banner) {
            $banners[$i] = tomedia($banner);
            $i++;
        }
        $config["banner"] = $banners;
        $config["banner_link"] = $banner_link;
        return $this->result($errno, $message, $config);
    }

    public function doPageSubmitUserInfo()
    {
        empty($GLOBALS["_GPC"]["__input"]["info"]["initial_driving_license_date"]) || ($GLOBALS["_GPC"]["__input"]["info"]["update_time"] = date("Y-m-d H:i:s"));
        pdo_update("slj123_pc_user", $GLOBALS["_GPC"]["__input"]["info"], array("wx_open_id" => $_SESSION["openid"]));
    }

    public function doPageCatchUploadFile()
    {
        if (!file_exists(ATTACHMENT_ROOT . "/images/{$GLOBALS["_W"]["uniacid"]}/" . date("Y/m/"))) {
            mkdir(ATTACHMENT_ROOT . "/images/{$GLOBALS["_W"]["uniacid"]}/" . date("Y/m/"), 0777, true);
        }
        foreach ($_FILES as $key => $value) {
            $result = move_uploaded_file($value["tmp_name"], ATTACHMENT_ROOT . "/images/{$GLOBALS["_W"]["uniacid"]}/" . date("Y/m/") . $value["name"]);
            pdo_update("slj123_pc_user", array($key => "/images/{$GLOBALS["_W"]["uniacid"]}/" . date("Y/m/") . $value["name"]), array("wx_open_id" => $_SESSION["openid"]));
        }
    }
//    public function doPageFetchPhoneRandomCode()
//    {
//        $Code = mt_rand(10000000, 99999999);
//        $Code = substr($Code, 1);
//        pdo_insert("slj123_pc_sms_code", array("openid" => $_SESSION["openid"], "code" => $Code));
//        $res = array();
//        try {
//            $res = \AliyunDySmsAPI::sendSms(trim($GLOBALS["_GPC"]["phone"]), $this->module["config"]["phone_random_code"]["\$setSignName"], $this->module["config"]["phone_random_code"]["\$setTemplateCode"], $this->module["config"]["phone_random_code"]["\$accessKeyId"], $this->module["config"]["phone_random_code"]["\$accessKeySecret"], array("code" => $Code), !0);
//        } catch (Exception $e) {
//            error_log("__FILE__:" . __FILE__ . ";" . "\n" . "__LINE__:" . __LINE__ . ";" . "\n" . "message:" . $e->getMessage() . "\n", 3, IA_ROOT . "/error_log.log");
//            echo "Message: " . $e->getMessage();
//        }
//        $this->result(0, "成功" . var_export($res, !0), method_exists("AliyunDySmsAPI", "sendSms"));
//    }
    public function doPageFetchPhoneRandomCode()
    {
        $Code = mt_rand(10000000, 99999999);
        $Code = substr($Code, 1);
        pdo_insert("slj123_pc_sms_code", array("openid" => $_SESSION["openid"], "code" => $Code));
        try {
            $message = "验证码$Code,您正在进行身份验证,请不要告诉别人!";
            \XlnSmsAPI::sendSms(trim($GLOBALS["_GPC"]["phone"]), $message);
        } catch (Exception $e) {
            error_log("__FILE__:" . __FILE__ . ";" . "\n" . "__LINE__:" . __LINE__ . ";" . "\n" . "message:" . $e->getMessage() . "\n", 3, IA_ROOT . "/error_log.log");
            echo "Message: " . $e->getMessage();
            exit;
        }
        $this->result(0, "success");
    }

    public function doPageCheckPhoneRandomCode()
    {
        pdo_delete("slj123_pc_sms_code", ["timestamp <" => date("Y-m-d H:i:s", TIMESTAMP - 60 * 5)]);
        $this->result(0, "成功", ["status" => pdo_delete("slj123_pc_sms_code", ["openid" => $_SESSION["openid"], "code" => $GLOBALS["_GPC"]["code"]])]);
    }
}